//
//  JSTLoginViewController.m
//  KYKJPackDemo
//
//  Created by 01 on 17/5/25.
//  Copyright © 2017年 ???. All rights reserved.
//

#import "JSTLoginViewController.h"
#import "JSTLoginCell.h"
//#import "SPKitExample.h"
@interface JSTLoginViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView                *headerView;

@property (nonatomic, strong) UIView                *footerView;

@property (nonatomic, strong) UITableView           *tabVeiw;

@property (nonatomic, strong) NSMutableArray        *labelData;

@property (nonatomic, strong) UIButton              *loginBtn;

@property (nonatomic, strong) UIButton              *codeBtn;

@property (nonatomic, strong) UITextField           *iPhoneTextFd;

@property (nonatomic, strong) UITextField           *codeTextFd;

@property (nonatomic, strong) NSTimer               *timer;

@property (nonatomic, strong) NSString              *codeStr;

@property (nonatomic, strong) NSString              *token;

@property (nonatomic, strong) NSString              *iphoneNum;

@property (nonatomic, strong) NSString              *imKey;

@property (nonatomic, strong) NSDictionary          *dataDic;

@property (nonatomic, strong) UIView                *otherLoginView;

@property (nonatomic, strong) NSArray               *permissions;

@property (nonatomic, strong) ThirdPartyUserModel   *tpUserModel;

@property (nonatomic, strong) UIView                *agreementView;

@property (nonatomic, strong) UIButton              *selectAgreementBtn;

@property (nonatomic, strong) UIButton              *agreementBtn;


@end

@implementation JSTLoginViewController
{
    NSInteger iPhoneNumLenght;
    NSInteger codeLenght;
    int currentTime;
}

- (void)dealloc
{
    [_timer invalidate];
    _timer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"登 录";
    
    [self createData];
    
    [self createContent];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
}

- (void) createData
{
    _labelData = [NSMutableArray arrayWithObjects:@"账 号:", @"验证码:", nil];
}

- (void) addTap
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(CaptureClick)];
    [self.view addGestureRecognizer:tap];
}

- (void) createContent
{
    self.tabVeiw.tableHeaderView = self.headerView;
    [self.view addSubview:self.tabVeiw];
    self.tabVeiw.userInteractionEnabled = YES;
    self.view.userInteractionEnabled = YES;
    
    [self addTap];
}

#pragma mark -- tabVeiw Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kCurrentScreenWidth(45);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JSTLoginCell *loginCell = [tableView dequeueReusableCellWithIdentifier:@"loginCell"];
    if (!loginCell)
    {
        loginCell = [[JSTLoginCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"loginCell"];
    }
    
    loginCell.selectionStyle = UITableViewCellSelectionStyleNone;
    [loginCell createContent:[_labelData safeObjectAtIndex:indexPath.row]];
    
    if (indexPath.row == 0)
    {
        [loginCell addSubview:self.iPhoneTextFd];
    }else
    {
        [loginCell addSubview:self.codeBtn];
        [loginCell addSubview:self.codeTextFd];
    }
    return loginCell;
}

//cell 分割线到头
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark textFd 事件捕捉
- (void)iPhoneTextFieldDidEditing:(UITextField *)textField
{
    // 设置手机号码自动空格
    if (textField.text.length > iPhoneNumLenght)
    {
        if (textField.text.length == 4 || textField.text.length == 9 )
        {
            //输入
            NSMutableString * str = [[NSMutableString alloc ] initWithString:textField.text];
            [str insertString:@" " atIndex:(textField.text.length-1)];
            textField.text = str;
        }if (textField.text.length >= 13 )
        {
            //输入完成
            textField.text = [textField.text substringToIndex:13];
            
            if (_timer) {
                return;
            }
            self.codeBtn.userInteractionEnabled = YES;
            self.codeBtn.selected = YES;
        }
        iPhoneNumLenght = textField.text.length;
        
    }else if (textField.text.length < iPhoneNumLenght)
    {
        //删除
        if (textField.text.length == 4 || textField.text.length == 9)
        {
            textField.text = [NSString stringWithFormat:@"%@",textField.text];
            textField.text = [textField.text substringToIndex:(textField.text.length-1)];
        }
        iPhoneNumLenght = textField.text.length;
        
        self.codeBtn.selected = NO;
        self.codeBtn.userInteractionEnabled = NO;
    }
}

- (void) codeTextFieldDidEditing:(UITextField *)textField
{
    if (textField.text.length >= 6)
    {
        // 输入完成
        textField.text = [textField.text substringToIndex:6];
        
        self.loginBtn.selected = NO;
        self.loginBtn.userInteractionEnabled = YES;
    }else
    {
        self.loginBtn.selected = YES;
        self.loginBtn.userInteractionEnabled = NO;
    }
}

// 隐藏键盘
- (void) CaptureClick
{
    [self.view endEditing:YES];
//    if (isIPhone4)
//    {
//        [self.view endEditing:YES];
//    }
}

// 获取验证码
- (void) GetvalidationCode:(NSString *)iphoneNum
{
    [self createTimer];
    
#warning 方便审核
    /*
    [JSTNewServer requestUserLogin:iphoneNum success:^(NSDictionary *dataDic)
    {
#warning 可能存在账号混乱
        DLog(@"----- dataDic = \n%@", dataDic);
        _iphoneNum = [JSTSystemInfo getStr:[dataDic valueForKey:@"username"]];
        _token = [dataDic valueForKey:@"token"];
        _codeStr = [NSString stringWithFormat:@"%@", [dataDic valueForKey:@"ma"]];
        _imKey = [JSTSystemInfo getStr:[dataDic valueForKey:@"taobao_key"]];
        _dataDic = [[NSDictionary alloc] initWithDictionary:dataDic];

    } error:^(NSString *errStr)
     {
         [self presentSheet:errStr];
    }];
     */
}

// 校验手机号
- (void) checkIphoneNum
{
    [self.view endEditing:YES];
    
    NSString *iphoneNum;
    if ([self.iPhoneTextFd.text containsString:@" "])
    {
        iphoneNum = [self.iPhoneTextFd.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    }else
    {
        iphoneNum = self.iPhoneTextFd.text;
    }
    
    NSString *regex = @"^[1][23578][0-9]{9}$";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    BOOL isMatch = [pred evaluateWithObject:iphoneNum];
    
    if (!isMatch)
    {
        [self presentSheet:@"请输入正确的手机号"];
        return;
    }
    [self GetvalidationCode:iphoneNum];
}

//
- (void) createTimer
{
    currentTime = 59;
    NSString *timeStr = [NSString stringWithFormat:@"%ds", currentTime];
    [self.codeBtn setTitle:timeStr forState:UIControlStateNormal];
    self.codeBtn.selected = NO;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1. target:self selector:@selector(countDown) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void) countDown
{
    currentTime--;
    if (currentTime > 0)
    {
        NSString *timeStr = [NSString stringWithFormat:@"%ds", currentTime];
        [self.codeBtn setTitle:timeStr forState:UIControlStateNormal];
        self.codeBtn.selected = NO;
        self.codeBtn.userInteractionEnabled = NO;
    }else
    {
        [_timer invalidate];
        _timer = nil;
        NSString *timeStr = @"获取验证码";
        [self.codeBtn setTitle:timeStr forState:UIControlStateNormal];
        self.codeBtn.selected = YES;
        self.codeBtn.userInteractionEnabled = YES;
    }
}

// 登录校验
- (void) loginCheck
{
//    if ([self.iPhoneTextFd.text containsString:@" "])
//    {
//        _iphoneNum = [self.iPhoneTextFd.text stringByReplacingOccurrencesOfString:@" " withString:@""];
//    }else
//    {
//        _iphoneNum = self.iPhoneTextFd.text;
//    }
    
    NSString *iphoneNum;
    if (self.iPhoneTextFd.text.length == 11 && ![self.iPhoneTextFd.text containsString:@" "])
    {
        iphoneNum = self.iPhoneTextFd.text;
    }else
    {
        iphoneNum = [self.iPhoneTextFd.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    DLog(@"----- \n iphoneNum = %@ \n _iphoneNum = %@", iphoneNum, _iphoneNum);
#warning 注释方便审核
    if (![iphoneNum isEqualToString:_iphoneNum])
    {
        [self presentSheet:@"当前手机号与获取验证码的手机号不对应"];
        return;
    }
    
    if (![_codeStr isEqualToString:self.codeTextFd.text])
    {
        [self presentSheet:@"验证码错误"];
        return;
    }

    
    [JSTSystemInfo cacheLoginToken:_token];
    [JSTSystemInfo cacheIphoneNum:_iphoneNum];
    [JSTSystemInfo cacheImKey:_imKey];
    
    NSMutableDictionary *userDict = [NSMutableDictionary dictionary];
    [userDict setValue:[JSTSystemInfo getStr:[_dataDic valueForKey:@"birth_day"]] forKey:@"birth_day"];
    [userDict setValue:[JSTSystemInfo getStr:[_dataDic valueForKey:@"birth_month"]] forKey:@"birth_month"];
    [userDict setValue:[JSTSystemInfo getStr:[_dataDic valueForKey:@"icon"]] forKey:@"icon"];
    [userDict setValue:[JSTSystemInfo getStr:[_dataDic valueForKey:@"ma"]] forKey:@"ma"];
    [userDict setValue:[JSTSystemInfo getStr:[_dataDic valueForKey:@"name"]] forKey:@"name"];
    [userDict setValue:[JSTSystemInfo getStr:[_dataDic valueForKey:@"sex"]] forKey:@"sex"];
    [userDict setValue:[JSTSystemInfo getStr:[_dataDic valueForKey:@"sign"]] forKey:@"sign"];
    [userDict setValue:[JSTSystemInfo getStr:[_dataDic valueForKey:@"taobao_key"]] forKey:@"taobao_key"];
    [userDict setValue:[JSTSystemInfo getStr:[_dataDic valueForKey:@"taobao_secret"]] forKey:@"taobao_secret"];
    [userDict setValue:[JSTSystemInfo getStr:[_dataDic valueForKey:@"token"]] forKey:@"token"];
    [userDict setValue:[JSTSystemInfo getStr:[_dataDic valueForKey:@"username"]] forKey:@"username"];
    [userDict setValue:[JSTSystemInfo getStr:[_dataDic valueForKey:@"uid"]] forKey:@"uid"];
    
    // user信息持久化
    [JSTSystemInfo cacheUserDict:userDict];
    
    // 初始化 IM
    /*
    //用户登出时调用
    [[SPKitExample sharedInstance] callThisBeforeISVAccountLogout];
    // 应用登陆成功后，调用SDK [[JSTSystemInfo iphoneNum] MD5] [@"123456" MD5]

    
    [[SPKitExample sharedInstance] callThisAfterISVAccountLoginSuccessWithYWLoginId:[[JSTSystemInfo iphoneNum] MD5]
                                                                           passWord:[@"123456" MD5]
                                                                    preloginedBlock:^{
                                                                        /// 可以显示会话列表页面
                                                                        DLog(@"preloginedBlock");
                                                                    } successBlock:^{
                                                                        //  到这里已经完成SDK接入并登录成功，你可以通过exampleMakeConversationListControllerWithSelectItemBlock获得会话列表
                                                                        /// 可以显示会话列表页面
//                                                                        [self changeConversationListViewController];
                                                                        DLog(@"successBlock");
                                                                    } failedBlock:^(NSError *aError) {
                                                                        if (aError.code == YWLoginErrorCodePasswordError || aError.code == YWLoginErrorCodePasswordInvalid || aError.code == YWLoginErrorCodeUserNotExsit)
                                                                        {
                                                                            [self presentSheet:@"加载失败"];
                                                                        }
                                                                    }];
     */
    
    
    [self backNavItemTapped];

}

- (UIView *)headerView
{
    if (!_headerView)
    {
        _headerView = [[UIView alloc] init];
        _headerView.frame = CGRectMake(0, 0, kDeviceWidth, kCurrentScreenWidth(35) + kCurrentScreenWidth(20) * 2);
        
        CGFloat titleX = 0;
        CGFloat titleY = 10;
        CGFloat titleW = kDeviceWidth;
        CGFloat titleH = kCurrentScreenWidth(35);
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.frame = CGRectMake(titleX, titleY, titleW, titleH);
        titleLabel.text = @"无需注册，手机号一步登录";
        titleLabel.textAlignment = NSTextAlignmentCenter;
        
        [_headerView addSubview:titleLabel];
    }
    return _headerView;
}

- (UIView *)footerView
{
    if (!_footerView)
    {
        _footerView = [[UIView alloc] init];
        _footerView.frame = CGRectMake(0, 0, kDeviceWidth, kCurrentScreenWidth(300));
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, .35)];
        lineView.backgroundColor = kSPLightGrayTextColor;
        [_footerView addSubview:lineView];
        
        CGFloat loginX = kCurrentScreenWidth(15);
        CGFloat loginY = kCurrentScreenWidth(20);
        CGFloat loginW = kDeviceWidth - loginX*2;
        CGFloat loginH = kCurrentScreenWidth(35);
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginBtn.frame = CGRectMake(loginX, loginY, loginW, loginH);
        [_loginBtn setTitle:@"登 录" forState:UIControlStateNormal];
        [_loginBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
        [_loginBtn setTitleColor:kSPGrayTextColor forState:UIControlStateSelected];
        [_loginBtn setBackgroundImage:[UIImage resizableImage:@"general_btn_normal"] forState:UIControlStateNormal];
        [_loginBtn setBackgroundImage:[UIImage resizableImage:@"general_btn_disable"] forState:UIControlStateSelected];
        
        
        _loginBtn.userInteractionEnabled = NO;
        _loginBtn.selected = YES;
        
        [_loginBtn addTarget:self action:@selector(loginCheck) forControlEvents:UIControlEventTouchUpInside];
        
        [_footerView addSubview:_loginBtn];
        
        [_footerView addSubview:self.otherLoginView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, _footerView.height - self.otherLoginView.height - kCurrentScreenWidth(35), kDeviceWidth, kCurrentScreenWidth(35))];
        label.text = @"--------- 第三方登录 ---------";
        label.font = kSystemFont(kCurrentScreenWidth(12));
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor grayColor];
        [_footerView addSubview:label];
    }
    return _footerView;
}

- (UITableView *)tabVeiw
{
    if (!_tabVeiw)
    {
        _tabVeiw = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tabVeiw.delegate = self;
        _tabVeiw.dataSource =self;
        _tabVeiw.tableFooterView = self.footerView;
    }
    return _tabVeiw;
}

- (UIButton *)codeBtn
{
    if (!_codeBtn)
    {
        _codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _codeBtn.frame = CGRectMake(kDeviceWidth - kCurrentScreenWidth(15) - kCurrentScreenWidth(75), kCurrentScreenWidth(5), kCurrentScreenWidth(75), kCurrentScreenWidth(35));
        [_codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_codeBtn setTitleColor:kSPGrayTextColor forState:UIControlStateNormal];
        [_codeBtn setTitleColor:kWhiteColor forState:UIControlStateSelected];
        [_codeBtn setBackgroundImage:[UIImage resizableImage:@"general_btn_disable"] forState:UIControlStateNormal];
        [_codeBtn setBackgroundImage:[UIImage resizableImage:@"general_btn_normal"] forState:UIControlStateSelected];
        
        _codeBtn.titleLabel.font = kSystemFont(kCurrentScreenWidth(10));
        _codeBtn.selected = NO;
        _codeBtn.userInteractionEnabled = NO;
        
        [_codeBtn addTarget:self action:@selector(checkIphoneNum) forControlEvents:UIControlEventTouchUpInside];
    }
    return _codeBtn;
}

- (UITextField *)iPhoneTextFd
{
    if (!_iPhoneTextFd)
    {
        _iPhoneTextFd = [[UITextField alloc] init];
        CGFloat iphoneFdX = EvaluationCellInset + kLoginLabelWidth;
        CGFloat iphoneFdY = EvaluationCellInset/2.;
        CGFloat iphoneFdW = kDeviceWidth - iphoneFdX - EvaluationCellInset;
        CGFloat iphoneFdH = kCurrentScreenWidth(35);
        _iPhoneTextFd.frame = CGRectMake(iphoneFdX, iphoneFdY, iphoneFdW, iphoneFdH);
        _iPhoneTextFd.placeholder = @"请输入手机号";
        _iPhoneTextFd.keyboardType = UIKeyboardTypeNumberPad;
        _iPhoneTextFd.clearButtonMode = UITextFieldViewModeWhileEditing;
        [_iPhoneTextFd addTarget:self action:@selector(iPhoneTextFieldDidEditing:) forControlEvents:UIControlEventEditingChanged];
    }
    return _iPhoneTextFd;
}

- (UITextField *)codeTextFd
{
    if (!_codeTextFd)
    {
        _codeTextFd = [[UITextField alloc] init];
        CGFloat codeFdX = EvaluationCellInset + kLoginLabelWidth;
        CGFloat codeFdY = EvaluationCellInset/2.;
        CGFloat codeFdW = kDeviceWidth - codeFdX - EvaluationCellInset*2 - self.codeBtn.width;
        CGFloat codeFdH = kCurrentScreenWidth(35);
        _codeTextFd.frame = CGRectMake(codeFdX, codeFdY, codeFdW, codeFdH);
        _codeTextFd.placeholder = @"请输入验证码";
        _codeTextFd.keyboardType = UIKeyboardTypeNumberPad;
        _codeTextFd.clearButtonMode = UITextFieldViewModeWhileEditing;
        [_codeTextFd addTarget:self action:@selector(codeTextFieldDidEditing:) forControlEvents:UIControlEventEditingChanged];
    }
    return _codeTextFd;
}

- (UIView *)otherLoginView
{
    if (!_otherLoginView) {
        _otherLoginView = [[UIView alloc] initWithFrame:CGRectMake(0, kCurrentScreenWidth(300) - kCurrentScreenWidth(100), kDeviceWidth, kCurrentScreenWidth(100))];
        UIButton *wxLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        wxLoginBtn.frame = CGRectMake((kDeviceWidth/2.) - kCurrentScreenWidth(50), kCurrentScreenWidth(10), kCurrentScreenWidth(35), kCurrentScreenWidth(35));
        [wxLoginBtn setImage:[UIImage imageNamed:@"login_pic_weixin"] forState:UIControlStateNormal];
        [wxLoginBtn addTarget:self action:@selector(changeWxLogin) forControlEvents:UIControlEventTouchUpInside];
        [_otherLoginView addSubview:wxLoginBtn];
        
        UIButton *qqLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        qqLoginBtn.frame = CGRectMake(kDeviceWidth/2. + kCurrentScreenWidth(15), kCurrentScreenWidth(10), kCurrentScreenWidth(35), kCurrentScreenWidth(35));
        [qqLoginBtn setImage:[UIImage imageNamed:@"login_pic_qq"] forState:UIControlStateNormal];
        [qqLoginBtn addTarget:self action:@selector(changeQqLogin) forControlEvents:UIControlEventTouchUpInside];
        [_otherLoginView addSubview:qqLoginBtn];
    }
    return _otherLoginView;
}

- (void) changeWxLogin
{
    [self sendAuthRequest];
}

- (void) changeQqLogin
{
    [self tencetnOAuthRequest];
}
//跳转微信授权
- (void) sendAuthRequest
{
    
}

// 跳转QQ授权
- (void) tencetnOAuthRequest
{
    
}

/** QQ登录回调 */
- (void)tencentDidLogin
{
    
}

/** 利用accessToken执行请求 */
- (void) otherLoginRequest:(NSString *)accessToken
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:_tpUserModel.platform forKey:@"form"];
    [dict setValue:_tpUserModel.nickName forKey:@"nickname"];
    [dict setValue:_tpUserModel.headimgurl forKey:@"figureurl"];
    [dict setValue:_tpUserModel.openId forKey:@"openid"];
    [dict setValue:_tpUserModel.sex forKey:@"gender"];
    [dict setValue:@"0QEKrhk5h0cJNnTfTjPZrhCZEPE43tZH" forKey:@"appkey"];
    [dict setValue:@"com.xt.thq2568" forKey:@"apkname"];
#warning 测试服务器数据
//    [dict setValue:[JSTSystemInfo userKey] forKey:@"appkey"];
//    [dict setValue:[JSTSystemInfo applicationIdentifier] forKey:@"apkname"];
    
    [JSTHttpClient sendRequest:@"http://kuaiyan.30lm.com/mobile/index.php?e=mobile/login.reg_check" requestMethod:AFRequestMethodGet parameters:dict success:^(id responseObject) {
        NSString *receiveStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        DLog(@"----- str = %@", receiveStr);
        NSData * data = [receiveStr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        DLog(@"------- dic = %@", dic);
        if ([[dic valueForKey:@"status"] integerValue] == 1)
        {
            
            
            NSMutableDictionary *dataDict = [NSMutableDictionary dictionaryWithDictionary:[dic valueForKey:@"data"]];
            
            [JSTSystemInfo cacheLoginToken:[dataDict valueForKey:@"token"]];
//            [JSTSystemInfo cacheIphoneNum:_iphoneNum];
            [JSTSystemInfo cacheImKey:[dataDict valueForKey:@"taobao_key"]];
            
            
            NSMutableDictionary *userDict = [NSMutableDictionary dictionary];
            [userDict setValue:[JSTSystemInfo getStr:[dataDict valueForKey:@"birth_day"]] forKey:@"birth_day"];
            [userDict setValue:[JSTSystemInfo getStr:[dataDict valueForKey:@"birth_month"]] forKey:@"birth_month"];
            [userDict setValue:[JSTSystemInfo getStr:[dataDict valueForKey:@"icon"]] forKey:@"icon"];
            [userDict setValue:[JSTSystemInfo getStr:[dataDict valueForKey:@"ma"]] forKey:@"ma"];
            [userDict setValue:[JSTSystemInfo getStr:[dataDict valueForKey:@"name"]] forKey:@"name"];
            [userDict setValue:[JSTSystemInfo getStr:[dataDict valueForKey:@"sex"]] forKey:@"sex"];
            [userDict setValue:[JSTSystemInfo getStr:[dataDict valueForKey:@"sign"]] forKey:@"sign"];
            [userDict setValue:[JSTSystemInfo getStr:[dataDict valueForKey:@"taobao_key"]] forKey:@"taobao_key"];
            [userDict setValue:[JSTSystemInfo getStr:[dataDict valueForKey:@"taobao_secret"]] forKey:@"taobao_secret"];
            [userDict setValue:[JSTSystemInfo getStr:[dataDict valueForKey:@"token"]] forKey:@"token"];
            [userDict setValue:[JSTSystemInfo getStr:[dataDict valueForKey:@"username"]] forKey:@"username"];
            [userDict setValue:[JSTSystemInfo getStr:[dataDict valueForKey:@"uid"]] forKey:@"uid"];
            
            // user信息持久化
            [JSTSystemInfo cacheUserDict:userDict];
    
            
            [self backNavItemTapped];
        }
    } failure:^(NSUInteger statusCode, NSString *error) {
        DLog(@"------ loginError = %@", error);
    }];
}

// 获取回调信息
- (void) getBaseResp:(id)notification
{

}

//使用code获取access token
- (void) getAccess_tokenWithCode:(NSString *)code
{
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", WeixinKey, WeixinSecret, code];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *dataStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                if ([ dict objectForKey:@"errcode"]) {
                    
                }else{
                    [[NSUserDefaults standardUserDefaults] setObject:[dict objectForKey:@"refresh_token"] forKey:kWeiXinRefreshToken];
                    [[NSUserDefaults standardUserDefaults] setObject:[dict objectForKey:@"openid"] forKey:kWeiXinOpenId];
                    [[NSUserDefaults standardUserDefaults] setObject:[dict objectForKey:@"access_token"] forKey:kWeiXinAccessToken];
                    NSString *str = [dict objectForKey:@"access_token"];
                    NSLog(@"------------- str = %@", str);
                    [self getUserInfoWithAccessToken:[dict objectForKey:@"access_token"] andOpenId:[dict objectForKey:@"openid"]];
                }
            }
        });
    });
}

/** 获取用户信息 */
- (void)getUserInfoWithAccessToken:(NSString *)accessToken andOpenId:(NSString *)openId
{
    NSString *urlString =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openId];
    NSURL *url = [NSURL URLWithString:urlString];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *dataStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (data)
            {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                if ([[dict objectForKey:@"errcode"] isKindOfClass:[NSNull class]])
                {
                    //AccessToken失效
                    [self getAccess_tokenWithRefreshToken:[[NSUserDefaults standardUserDefaults]objectForKey:kWeiXinRefreshToken]];
                }else
                {
                    //获取需要的用户数据
                    _tpUserModel = [[ThirdPartyUserModel alloc] init];
                    _tpUserModel.nickName = dict[@"nickname"];
                    _tpUserModel.headimgurl = dict[@"headimgurl"];
                    _tpUserModel.platform = weixinPlatform;
                    
                    [self otherLoginRequest:openId];
                }
            }
        });
    });
}

// 使用RefreshToken刷新AccessToken该接口调用后，如果AccessToken未过期，则刷新有效期，如果已过期，更换AccessToken。
- (void) getAccess_tokenWithRefreshToken:(NSString *)refreshToken
{
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@",WeixinKey,refreshToken];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *dataStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                if ([dict objectForKey:@"errcode"]) {
                    //授权过期
                    [self presentSheet:@"授权过期"];
                }else{
                    //重新使用AccessToken获取信息
                    [self getUserInfoWithAccessToken:[dict objectForKey:@"access_token"] andOpenId:[dict objectForKey:@"openid"]];
                }
            }
        });
    });
}

- (void)backNavItemTapped
{
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
